package org.budo.tencent.response;

import java.util.Map;

import org.budo.support.http.client.Response;
import org.budo.support.lang.util.ArrayUtil;
import org.budo.support.lang.util.NumberUtil;
import org.budo.support.lang.util.StringUtil;
import org.budo.support.servlet.util.QueryStringUtil;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Getter
@Setter
@Slf4j
public class TokenResponse extends AbstractResponse {
    private static final long serialVersionUID = -2364102915582135300L;

    private String accessToken;

    private Integer expiresIn;

    public TokenResponse() {
    }

    public TokenResponse(Response response) {
        this.setResponse(response);

        String responseBody = response.getBody();
        Map<String, String[]> responseMap = QueryStringUtil.queryStringToMap(responseBody);

        String accessToken = ArrayUtil.first(responseMap.get("access_token"));
        if (StringUtil.isEmpty(accessToken)) {
            log.error("#40 response=" + response.toSimpleString());
            return;
        }

        this.setAccessToken(accessToken);

        String expiresInValue = ArrayUtil.first(responseMap.get("expires_in"));
        Integer expiresIn = NumberUtil.toInteger(expiresInValue);

        this.setExpiresIn(expiresIn);
    }
}